import Mock from 'mockjs'

// 角色数据
const roleData = [
  {
    id: '1',
    name: '超级管理员',
    description: '拥有系统所有权限',
    permissions: [
      { id: '1', name: '用户管理' },
      { id: '2', name: '角色管理' },
      { id: '3', name: '权限管理' },
      { id: '4', name: '系统设置' },
      { id: '5', name: '数据统计' },
      { id: '6', name: '日志查看' }
    ]
  },
  {
    id: '2',
    name: '管理员',
    description: '拥有大部分管理权限',
    permissions: [
      { id: '1', name: '用户管理' },
      { id: '2', name: '角色管理' },
      { id: '7', name: '商品管理' },
      { id: '8', name: '订单管理' },
      { id: '9', name: '客户管理' }
    ]
  },
  {
    id: '3',
    name: '运营专员',
    description: '负责日常运营工作',
    permissions: [
      { id: '7', name: '商品管理' },
      { id: '8', name: '订单管理' },
      { id: '9', name: '客户管理' },
      { id: '10', name: '库存管理' }
    ]
  },
  {
    id: '4',
    name: '财务专员',
    description: '负责财务相关工作',
    permissions: [
      { id: '11', name: '财务管理' },
      { id: '12', name: '报表查看' },
      { id: '13', name: '账目核对' }
    ]
  },
  {
    id: '5',
    name: '普通用户',
    description: '基础用户权限',
    permissions: [
      { id: '14', name: '基础查看' },
      { id: '15', name: '个人信息' }
    ]
  }
]

// 生成用户列表数据
const generateUserList = (count = 100) => {
  const users = []
  
  for (let i = 1; i <= count; i++) {
    const roleIds = Mock.Random.pick([
      ['1'], ['2'], ['3'], ['4'], ['5'],
      ['2', '3'], ['3', '4'], ['4', '5']
    ])
    
    const userRoles = roleIds.map(roleId => roleData.find(r => r.id === roleId))
    const userPermissions = [...new Set(userRoles.flatMap(role => role.permissions))]
    
    users.push({
      id: i,
      username: Mock.Random.word(5, 10),
      nickname: Mock.Random.cname(),
      realName: Mock.Random.cname(),
      email: Mock.Random.email(),
      phone: `1${Mock.Random.string('number', 10)}`,
      avatar: Mock.Random.image('100x100', Mock.Random.color(), '#FFF', 'Avatar'),
      roleIds: roleIds,
      roles: userRoles,
      permissions: userPermissions,
      status: Mock.Random.pick(['active', 'inactive']),
      companyName: Mock.Random.pick(['供应链科技公司', '物流集团', '贸易公司', '制造企业', '零售连锁']),
      departmentId: Mock.Random.pick(['1', '1-1', '1-2', '2', '2-1', '2-2', '2-3', '3', '3-1', '3-2']),
      departmentName: Mock.Random.pick(['总经理办公室', '人事部', '财务部', '技术部', '前端开发组', '后端开发组', '测试组', '运营部', '市场推广组', '客户服务组']),
      position: Mock.Random.pick(['总监', '经理', '主管', '专员', '助理']),
      employeeId: `EMP${String(i).padStart(4, '0')}`,
      gender: Mock.Random.pick(['male', 'female', 'other']),
      birthday: Mock.Random.date('yyyy-MM-dd'),
      hiredAt: Mock.Random.date('yyyy-MM-dd'),
      remark: Mock.Random.sentence(5, 15),
      lastLoginAt: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
      loginCount: Mock.Random.integer(0, 500),
      createdAt: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
      updatedAt: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
      stats: {
        orderCount: Mock.Random.integer(0, 100),
        taskCount: Mock.Random.integer(0, 50),
        messageCount: Mock.Random.integer(0, 200),
        documentCount: Mock.Random.integer(0, 80)
      }
    })
  }
  
  return users
}

const userList = generateUserList(100)

// 获取用户列表
Mock.mock(/\/api\/v1\/users(\?.*)?$/, 'get', (options) => {
  const url = new URL(options.url, 'http://localhost')
  const page = parseInt(url.searchParams.get('page')) || 1
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 10
  const keyword = url.searchParams.get('keyword') || ''
  const role = url.searchParams.get('role') || ''
  const status = url.searchParams.get('status') || ''
  
  // 过滤数据
  let filteredUsers = [...userList]
  
  if (keyword) {
    filteredUsers = filteredUsers.filter(user => 
      user.username.includes(keyword) || 
      user.realName.includes(keyword) || 
      user.email.includes(keyword)
    )
  }
  
  if (role) {
    filteredUsers = filteredUsers.filter(user => user.role === role)
  }
  
  if (status) {
    filteredUsers = filteredUsers.filter(user => user.status === status)
  }
  
  // 分页
  const total = filteredUsers.length
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const paginatedUsers = filteredUsers.slice(start, end)
  
  return {
    code: 200,
    message: '获取成功',
    data: {
      list: paginatedUsers,
      pagination: {
        current: page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize)
      }
    }
  }
})

// 获取用户详情
Mock.mock(/\/api\/v1\/users\/\d+$/, 'get', (options) => {
  const url = options.url
  const userId = parseInt(url.match(/\/users\/(\d+)$/)[1])
  
  const user = userList.find(u => u.id === userId)
  
  if (user) {
    return {
      code: 200,
      message: '获取成功',
      data: user
    }
  } else {
    return {
      code: 404,
      message: '用户不存在',
      data: null
    }
  }
})

// 创建用户
Mock.mock('/api/v1/users', 'post', (options) => {
  const userData = JSON.parse(options.body)
  
  // 检查用户名是否已存在
  const existingUser = userList.find(u => u.username === userData.username)
  if (existingUser) {
    return {
      code: 400,
      message: '用户名已存在',
      data: null
    }
  }
  
  // 检查邮箱是否已存在
  const existingEmail = userList.find(u => u.email === userData.email)
  if (existingEmail) {
    return {
      code: 400,
      message: '邮箱已被注册',
      data: null
    }
  }
  
  // 创建新用户
  const newUser = {
    id: userList.length + 1,
    ...userData,
    avatar: userData.avatar || Mock.Random.image('100x100', Mock.Random.color(), '#FFF', 'Avatar'),
    status: userData.status || 'active',
    createTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
    updateTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss')
  }
  
  userList.push(newUser)
  
  return {
    code: 200,
    message: '创建成功',
    data: newUser
  }
})

// 更新用户
Mock.mock(/\/api\/v1\/users\/\d+$/, 'put', (options) => {
  const url = options.url
  const userId = parseInt(url.match(/\/users\/(\d+)$/)[1])
  const updateData = JSON.parse(options.body)
  
  const userIndex = userList.findIndex(u => u.id === userId)
  
  if (userIndex === -1) {
    return {
      code: 404,
      message: '用户不存在',
      data: null
    }
  }
  
  // 检查用户名是否重复（排除当前用户）
  if (updateData.username) {
    const existingUser = userList.find(u => u.username === updateData.username && u.id !== userId)
    if (existingUser) {
      return {
        code: 400,
        message: '用户名已存在',
        data: null
      }
    }
  }
  
  // 检查邮箱是否重复（排除当前用户）
  if (updateData.email) {
    const existingEmail = userList.find(u => u.email === updateData.email && u.id !== userId)
    if (existingEmail) {
      return {
        code: 400,
        message: '邮箱已被注册',
        data: null
      }
    }
  }
  
  // 更新用户信息
  userList[userIndex] = {
    ...userList[userIndex],
    ...updateData,
    updateTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss')
  }
  
  return {
    code: 200,
    message: '更新成功',
    data: userList[userIndex]
  }
})

// 删除用户
Mock.mock(/\/api\/v1\/users\/\d+$/, 'delete', (options) => {
  const url = options.url
  const userId = parseInt(url.match(/\/users\/(\d+)$/)[1])
  
  const userIndex = userList.findIndex(u => u.id === userId)
  
  if (userIndex === -1) {
    return {
      code: 404,
      message: '用户不存在',
      data: null
    }
  }
  
  // 删除用户
  userList.splice(userIndex, 1)
  
  return {
    code: 200,
    message: '删除成功',
    data: null
  }
})

// 批量删除用户
Mock.mock('/api/v1/users/batch', 'delete', (options) => {
  const { userIds } = JSON.parse(options.body)
  
  if (!userIds || !Array.isArray(userIds) || userIds.length === 0) {
    return {
      code: 400,
      message: '请选择要删除的用户',
      data: null
    }
  }
  
  // 批量删除用户
  const deletedCount = userIds.length
  userIds.forEach(userId => {
    const userIndex = userList.findIndex(u => u.id === userId)
    if (userIndex !== -1) {
      userList.splice(userIndex, 1)
    }
  })
  
  return {
    code: 200,
    message: `成功删除 ${deletedCount} 个用户`,
    data: {
      deletedCount
    }
  }
})

// 更新用户状态
Mock.mock(/\/api\/v1\/users\/\d+\/status$/, 'patch', (options) => {
  const url = options.url
  const userId = parseInt(url.match(/\/users\/(\d+)$/)[1])
  const { status } = JSON.parse(options.body)
  
  const user = userList.find(u => u.id === userId)
  
  if (!user) {
    return {
      code: 404,
      message: '用户不存在',
      data: null
    }
  }
  
  // 更新状态
  user.status = status
  user.updateTime = Mock.Random.datetime('yyyy-MM-dd HH:mm:ss')
  
  return {
    code: 200,
    message: '状态更新成功',
    data: {
      id: user.id,
      status: user.status
    }
  }
})

// 重置用户密码
Mock.mock(/\/api\/v1\/users\/\d+\/reset-password$/, 'post', (options) => {
  const url = options.url
  const userId = parseInt(url.match(/\/users\/(\d+)$/)[1])
  
  const user = userList.find(u => u.id === userId)
  
  if (!user) {
    return {
      code: 404,
      message: '用户不存在',
      data: null
    }
  }
  
  // 生成新密码
  const newPassword = Mock.Random.string('number', 6)
  user.password = newPassword
  user.updateTime = Mock.Random.datetime('yyyy-MM-dd HH:mm:ss')
  
  return {
    code: 200,
    message: '密码重置成功',
    data: {
      id: user.id,
      newPassword
    }
  }
})

// 获取用户统计信息
Mock.mock('/api/v1/users/stats', 'get', () => {
  const totalUsers = userList.length
  const activeUsers = userList.filter(u => u.status === 'active').length
  const inactiveUsers = userList.filter(u => u.status === 'inactive').length
  
  const roleStats = {}
  userList.forEach(user => {
    user.roles?.forEach(role => {
      roleStats[role.name] = (roleStats[role.name] || 0) + 1
    })
  })
  
  const departmentStats = {}
  userList.forEach(user => {
    departmentStats[user.departmentName] = (departmentStats[user.departmentName] || 0) + 1
  })
  
  return {
    code: 200,
    message: '获取成功',
    data: {
      total: totalUsers,
      statusStats: {
        active: activeUsers,
        inactive: inactiveUsers
      },
      roleStats,
      departmentStats,
      recentUsers: userList.slice(-5).map(user => ({
        id: user.id,
        username: user.username,
        nickname: user.nickname,
        realName: user.realName,
        createdAt: user.createdAt
      }))
    }
  }
})

// 用户角色分配
Mock.mock('/api/v1/users/assign-roles', 'post', (options) => {
  const { userIds, roleIds } = JSON.parse(options.body)
  
  if (!userIds || !Array.isArray(userIds) || userIds.length === 0) {
    return {
      code: 400,
      message: '请选择要分配角色的用户',
      data: null
    }
  }
  
  if (!roleIds || !Array.isArray(roleIds) || roleIds.length === 0) {
    return {
      code: 400,
      message: '请选择要分配的角色',
      data: null
    }
  }
  
  // 获取角色信息
  const assignRoles = roleIds.map(roleId => roleData.find(r => r.id === roleId)).filter(Boolean)
  const assignPermissions = [...new Set(assignRoles.flatMap(role => role.permissions))]
  
  // 更新用户角色
  let updatedCount = 0
  userIds.forEach(userId => {
    const user = userList.find(u => u.id === userId)
    if (user) {
      user.roleIds = roleIds
      user.roles = assignRoles
      user.permissions = assignPermissions
      user.updatedAt = Mock.Random.datetime('yyyy-MM-dd HH:mm:ss')
      updatedCount++
    }
  })
  
  return {
    code: 200,
    message: `成功为 ${updatedCount} 个用户分配角色`,
    data: {
      updatedCount,
      assignedRoles: assignRoles.map(r => r.name)
    }
  }
})

// 获取可用角色列表
Mock.mock('/api/v1/roles', 'get', () => {
  return {
    code: 200,
    message: '获取成功',
    data: roleData
  }
}) 